package recommend

import (
	"context"
	"fmt"
	"golang.org/x/net/html"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/deepseek"

	"github.com/zeromicro/go-zero/core/logx"
)

type InitItemLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 香水时代的数据用作 Item
func NewInitItemLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InitItemLogic {
	return &InitItemLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *InitItemLogic) InitItem() (*types.BackendDiagnoseResp, error) {
	//var wg = &sync.WaitGroup{}
	baseURLs := []string{
		"https://www.nosetime.com/brand.php?id=10018780&uid=53381028",
		//"https://www.nosetime.com/brand.php?id=10098636&uid=53381028",
	}
	for _, v := range baseURLs {
		params := url.Values{}
		params.Add("method", "jump")
		params.Add("page", "4")
		params.Add("token", "2e9903d7b6f60bbb52f149c28b64aa4b")
		params.Add("canbuy", "0")
		params.Add("orderby", "hot")
		resp, err := http.Post(v, "application/json;charset=UTF-8", strings.NewReader(params.Encode()))
		if err != nil {
			return nil, err
		}
		defer resp.Body.Close() // 确保响应体被关闭

		// 读取响应体
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			fmt.Println("读取响应失败: %v", err)
		}
		doc, err := html.Parse(strings.NewReader(string(body)))
		if err != nil {
			fmt.Println("Error parsing HTML:", err)
			return nil, err
		}
		l.traverse(doc)
		urlMap := make(map[string]struct{})
		var newUrl []string
		if len(urls) > 0 {
			for _, v := range urls {
				if len(v) > 0 {
					if _, ok := urlMap[v]; !ok {
						urlMap[v] = struct{}{}
						newUrl = append(newUrl, "https://www.nosetime.com/"+v)
					}
				}
			}
		}
		//爬取详情页香评
		for _, v := range newUrl {
			sonResp, err := http.Post(v, "application/json;charset=UTF-8", strings.NewReader(params.Encode()))
			if err != nil {
				return nil, err
			}
			defer sonResp.Body.Close() // 确保响应体被关闭

			// 读取响应体
			sonBody, err := ioutil.ReadAll(sonResp.Body)
			if err != nil {
				fmt.Println("读取响应失败: %v", err)
			}
			l.sonParseUrls(string(sonBody))
		}
	}
	//var labelsMap = make(map[string]struct{})
	//wg.Add(len(contentList))
	var itemId uint64
	fmt.Println(contentList, "contentList")
	for _, v := range contentList {
		lables := l.askDS(v)
		if len(lables) > 0 {
			itemId++
			l.createItem(globalkey.GorseBLogPostPrefix+strconv.FormatUint(itemId, 10), lables)
			l.createItem(globalkey.GorseKnowledgeBasePrefix+strconv.FormatUint(itemId, 10), lables)
		}
	}
	//wg.Wait()
	return nil, nil
}

// 香水列表
var urls []string

func (l *InitItemLogic) traverse(n *html.Node) {
	if n.Type == html.ElementNode && n.Data == "a" {
		for _, attr := range n.Attr {
			if attr.Key == "href" {
				if strings.Contains(attr.Val, "/xiangshui/") {
					urls = append(urls, attr.Val)
				}
				break
			}
		}
	}
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		l.traverse(c)
	}
	return
}

// 香评列表
func (l *InitItemLogic) sonParseUrls(body string) {
	doc, err := html.Parse(strings.NewReader(body))
	if err != nil {
		fmt.Println("Error parsing HTML:", err)
		return
	}
	l.sonTraverse(doc)
}

var contentList []string

func (l *InitItemLogic) sonTraverse(n *html.Node) {
	if n.Type == html.ElementNode && n.DataAtom.String() == "div" {
		for _, attr := range n.Attr {
			//内容部分
			if attr.Key == "class" && attr.Val == "hfshow" {
				lastChild := n.LastChild
				if len(lastChild.Data) > 5 {
					contentList = append(contentList, lastChild.Data)
				}
				break
			}
		}
	}
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		l.sonTraverse(c)
	}
	return
}
func (l *InitItemLogic) askDS(v string) []string {
	//defer func() {
	//	wg.Done()
	//}()
	//询问deepseek 获取标签
	var labels []string
	aiResp, err := deepseek.AskDeepSeekAI([]string{v + " 请从 木质香,花香调,绅士风,优雅感,商务款,约会香,烟草香,暖男风,安全感,乌木调,焚香感,持久款,美食调,草本香,广藿香,麝香调,白花香,清新感,脂粉气,中性香,自然风,暖香,伪体香,蜜瓜香,清新调 中选出三个词作为这段话的标签使用，词语与词语之间用英文逗号隔开，方便处理,请严格按照要求回答！"}, globalkey.DeepseekContentTypeDefault)
	if err != nil {
		logx.Infow("DeferredInquireAiMq.execService AskDeepSeekAI err", logx.Field("detail", err.Error()))
	}
	if choices, ok := aiResp["choices"]; ok {
		for _, choice := range choices.([]any) {
			if msg, ok := choice.(map[string]any)["message"]; ok {
				var messageMap = msg.(map[string]any)
				var content string
				if c, ok := messageMap["content"]; ok {
					content = c.(string)
				}

				if len(content) > 0 {
					c := strings.Split(content, ",")
					labels = append(labels, c...)
				}
			}
		}
	}
	return labels
}

func (l *InitItemLogic) createItem(itemId string, labels []string) {
	err := l.svcCtx.GorseClient.CreateItem(
		l.svcCtx.Config.Query.GorseUrl,
		itemId, "", "0",
		labels, strings.Split(strconv.FormatInt(int64(globalkey.AttachmentLogKbEntry), 10), ","))
	fmt.Println("createItem itemId labels", itemId, labels)
	fmt.Println("createItem err", err)
	if err != nil {
		logx.Infow("")
	}
}
